#include <map>
#include "World.h"
#include "Controller.h"
void World::SendWorldMsg( PapaBallMsg msg )
{
	if(mState != StateType::AddTimeEnd)
		return;
	ControllerContainerType::iterator iter;
	for(iter = mControllerContainer.begin();iter!=mControllerContainer.end();iter++)
	{
		iter->second->Send(msg);
	}
}

void World::SendMsg( Ogre::String Target,PapaBallMsg msg )
{
	if(mState != StateType::AddTimeEnd)
		return;
	ControllerContainerType::iterator iter;
	iter = mControllerContainer.find(Target);
	if (iter==mControllerContainer.end()) return;
	iter->second->Send(msg);
}

void World::Destroy()
{
	ControllerContainerType::iterator iter;
	for(iter = mControllerContainer.begin();iter!=mControllerContainer.end();iter++)
	{
		delete iter->second;
	}
	mControllerContainer.clear();
}

void World::RegisterController( Ogre::String name,AbstractController* controller )
{
	mControllerContainer.insert(std::make_pair<Ogre::String,AbstractController*>(name,controller));
	controller->setWorld(this);
	controller->SetControllerName(name);
	controller->SetInputMgr(mInputMgr);
	controller->Initialization();
}

void World::DestroyController( Ogre::String name )
{
	ControllerContainerType::iterator iter;
	iter = mControllerContainer.find(name);
	if (iter==mControllerContainer.end()) return;
	delete iter->second;
	mControllerContainer.erase(iter);
}

AbstractController* World::GetController( Ogre::String name )
{
	ControllerContainerType::iterator iter;
	iter = mControllerContainer.find(name);
	if (iter==mControllerContainer.end()) return NULL;
	return iter->second;
}

void World::AddTime( Ogre::Real deltaTime )
{
	mState = StateType::PhysicUpdate;

	ControllerContainerType::iterator iter;

	mState=StateType::AddTimeStart;
	for(iter =mControllerContainer.begin();iter!=mControllerContainer.end();iter++)
		iter->second->AddTimeStart(deltaTime);

	mState=StateType::AddingTime;
	for(iter =mControllerContainer.begin();iter!=mControllerContainer.end();iter++)
		iter->second->AddTime(deltaTime);

	mState=StateType::AddTimeEnd;
	for(iter =mControllerContainer.begin();iter!=mControllerContainer.end();iter++)
		iter->second->AddTimeEnded(deltaTime);

	mState=StateType::Ready;

}


World::~World()
{
	if(!bDestroy)
		this->Destroy();
}
